/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package executing;

import executingimpl.runner.BuildProcessRunner;
import executor.ExecutionResult;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ryuju
 */
public abstract class AbstractProcessRunner implements IProcessRunner{
    
    public static final int BUFFER_SIZE = 2048;
    
    @Override
    public ExecutionResult run(List<String> cmdList)
    {
        return run(cmdList, null);
    }
    
    
    
    protected int readStream(BufferedInputStream stm, StringWriter outStm, boolean blockMode)
    {
        int totalReadBytes = 0;
        boolean canRead = true;
        boolean isEof = false;
        
        byte[] buffer = new byte[BUFFER_SIZE];
        int blockCnt = 0;
        
        while(canRead)
        {
            try {
                int maxReadLen = 0;
            
                if(blockMode)
                {
                    maxReadLen = buffer.length;
                }
                else
                {
                   maxReadLen = stm.available();
                   maxReadLen = Math.min(maxReadLen, buffer.length);
                }
                
                if(0 < maxReadLen)
                {
                    blockCnt = 0;
                    int readBytes = stm.read(buffer, 0, maxReadLen);
                    if(0 > readBytes)
                    {
                        canRead = false;
                        isEof = true;
                    }
                    
                    if(0 < readBytes)
                    {
                        totalReadBytes += readBytes;
                        outStm.write(new String(buffer, 0, readBytes));
                    }
                    
                }
                else
                {
                    blockCnt++;
                    if(2 < blockCnt)
                    {
                        canRead = false;
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(AbstractProcessRunner.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        if(isEof)
            return -1;
        
        return totalReadBytes;
    }
}
